import { getProvince, getChildArea } from "@/api/system/division"
import { treeData } from '@/views/businessManage/common/propertyTree'
import { getId, checkId, save, update, getById } from '@/api/businessManage/dataLoader/otherData'
import { ElMessage } from 'element-plus'
import useOtherDataStore from '@/store/modules/otherData'

const otherData = useOtherDataStore()
const { prevData } = storeToRefs(otherData)

export default function () {
  const router = useRouter()
  const route = useRoute()
  const subjectId = route.query.id
  const initForm = () => ({})
  let form = ref(initForm())

  let baseUrl
  let formName
  let idName
  let numField
  let pathName

  treeData.map(item => {
    let compareValue
    if (route.query.curKey) {
      compareValue = route.query.curKey
    } else {
      compareValue = route.path.split('/').slice(-1)
    }
    let objItem = item.children.find(itemChil => itemChil.pathName == compareValue)
    if (objItem) {
      baseUrl = objItem.baseUrl
      formName = objItem.label
      idName = objItem.idName
      pathName = objItem.pathName
      numField = objItem.numField || 'id'
    }
  })


  // 查询+省市县
  const queryData = reactive({
    queryParams: {},
    provinceData: [],
    cityData: [],
    areaData: [],
    total: 0
  })
  const { queryParams, provinceData, cityData, areaData } = toRefs(queryData)
  const getProvinceData = () => {
    getProvince().then(res => {
      if (res.code == 200) {
        provinceData.value = res.data
      }
    })
  }
  const chooseProvince = (value) => {
    queryParams.value.cityId = null
    queryParams.value.countyId = null
    queryParams.value.city = null
    queryParams.value.county = null
    cityData.value = []
    areaData.value = []
    getChildArea(value).then(response => {
      cityData.value = response.data
    })
    queryParams.value.province = provinceData.value.find(item => item.id == value).name
  }
  const chooseCity = (value) => {
    queryParams.value.countyId = null
    queryParams.value.county = null
    areaData.value = []
    getChildArea(value).then(response => {
      areaData.value = response.data
    })
    queryParams.value.city = cityData.value.find(item => item.id == value).name
  }
  const chooseCounty = (value) => {
    queryParams.value.county = areaData.value.find(item => item.id == value).name
  }

  const chooseFormProvince = (value) => {
    if (value) {
      form.value.cityId && (form.value.cityId = '')
      form.value.countyId && (form.value.countyId = '')
      cityData.value = []
      areaData.value = []
      getChildArea(value).then(response => {
        cityData.value = response.data
      })
      form.value.province = provinceData.value.find(item => item.id == value)?.name
      form.value[numField] = ''
    }
  }

  const chooseFormCity = (value) => {
    if (value) {
      form.value.countyId && (form.value.countyId = '')
      areaData.value = []
      getChildArea(value).then(response => {
        areaData.value = response.data
      })
      form.value.city = cityData.value.find(item => item.id == value)?.name
      form.value[numField] = ''
    }
  }

  const chooseFormCounty = (value) => {
    if (value) {
      form.value.county = areaData.value.find(item => item.id == value).name
      form.value[numField] = ''
    }
  }

  // 附件
  const uploadSuccess = (type, files) => {
    form.value[type] = files.map(item => item.attachId).join(',')
    addRef.value.clearValidate(type)
  }

  const deleteFile = (type, files) => {
    form.value[type] = files.map(item => item.attachId).join(',')
  }

  const resetDrawer = () => {
    let { provinceId, cityId, countyId, province, city, county } = form.value
    let keys = Object.keys(form.value)
    keys.map(item => {
      form.value[item] = ''
    })
    Object.assign(form.value, initForm())
    prevData.value = { provinceId, cityId, countyId, province, city, county }
    console.log(prevData.value)
  }
  const closeDrawer = () => {
    resetDrawer()
    router.go(-1)
  }

  const checkIdValid = (rule, value, callback) => {
    checkId(baseUrl, { id: value, smId: subjectId, key: form.value[idName] || '' }).then(res => {
      if (res.data) {
        callback()
      } else {
        callback(new Error('编号重复！'));
      }
    })
  }

  const addRef = ref()
  const queryTable = ref()
  const confirmAndSave = () => {
    addRef.value.validate((valid, fields) => {
      if (valid) {
        save(baseUrl, { ...form.value, smId: subjectId }).then(res => {
          ElMessage.success('保存成功！')
          resetDrawer()
          nextTick(() => {
            addRef.value.clearValidate()
            addRef.value.scrollToField('provinceId')
          })
          let { provinceId, cityId, countyId, province, city, county } = prevData.value
          form.value.province = province
          form.value.provinceId = provinceId
          form.value.city = city
          form.value.cityId = cityId
          form.value.county = county
          form.value.countyId = countyId
        })
      } else {
        addRef.value.scrollToField(Object.keys(fields)[0])
      }
    })
  }
  const addDrawer = ref(true)
  const confirmClick = () => {
    addRef.value.validate((valid, fields) => {
      if (valid) {
        if (form.value[idName]) {
          update(baseUrl, { ...form.value, smId: subjectId }).then(res => {
            ElMessage.success('修改成功！')
            // router.go(-1)
            closeDrawer()
          })
        } else {
          save(baseUrl, { ...form.value, smId: subjectId }).then(res => {
            ElMessage.success('保存成功！')
            // router.go(-1)
            closeDrawer()
          })
        }
      } else {
        addRef.value.scrollToField(Object.keys(fields)[0])
      }
    })
  }
  const openDrawer = () => {
    addRef.value.clearValidate()
    console.log(form.value, !form.value.id, prevData.value)
    if(!form.value.id){
      form.value.province = prevData.value.province
      form.value.city = prevData.value.city
      form.value.county = prevData.value.county
      form.value.provinceId = prevData.value.provinceId
      form.value.cityId = prevData.value.cityId
      form.value.countyId = prevData.value.countyId
      console.log(form.value)
    }
  }
  const drawerLoading = ref(false)
  const getFormDetail = (id) => {
    provinceData.value = []
    drawerLoading.value = true
    getById(baseUrl, id).then(res => {
      form.value = res.data
      getChildArea(form.value.provinceId).then(response => {
        cityData.value = response.data
      })
      getChildArea(form.value.cityId).then(response => {
        areaData.value = response.data
      })
      drawerLoading.value = false
      if (pathName == 'geophySvyDataTable') {
        form.value.resultType = form.value.resultType.split(',')
      }
    })
  }

  const notHasId = ['internalData']
  watch(() => [form.value.province, form.value.city, form.value.county, form.value[numField]], () => {
    if (notHasId.includes(pathName)) return
    !form.value.city && (form.value.city = prevData.value.city)
    !form.value.county && (form.value.county = prevData.value.county)
    let { province, city, county } = form.value
    if (form.value[numField]) return
    if (form.value.province && form.value.city && form.value.county) {
      getId(baseUrl, { province, city, county, smId: route.query.id }).then(res => {
        form.value[numField] = res.data
      })
    }
  })

  // watch(() => route, (newVal, oldVal) => {
  watch(() => route.query.detailId, (newVal, oldVal) => {
    getProvinceData()
    let routeName = route.name.includes('-') && route.name.split('-')[1] || route.name
    if (route.query.detailId && routeName == pathName) {
      getFormDetail(route.query.detailId)
    }
  }, { immediate: true })

  watch(() => form.value.provinceId, () => {
    getChildArea(form.value.provinceId).then(response => {
      cityData.value = response.data
    })
  })
  watch(() => form.value.cityId, () => {
    getChildArea(form.value.cityId).then(response => {
      areaData.value = response.data
    })
  })

  return {
    route,
    form,
    queryData,
    baseUrl,
    formName,
    idName,
    initForm,
    getProvinceData,
    chooseProvince,
    chooseCity,
    chooseCounty,
    chooseFormProvince,
    chooseFormCity,
    chooseFormCounty,
    uploadSuccess,
    deleteFile,
    openDrawer,
    closeDrawer,
    checkIdValid,
    addRef,
    queryTable,
    confirmAndSave,
    addDrawer,
    confirmClick,
    drawerLoading
  }
}
